import { getCookie, getQueryString } from ".";

export const setPv_new = (page_id: number, paras: { additional?: { [key: string | number]: string | number; } } = {})=> {
    let dataStr = 'page_id=' + page_id;

    if (paras.additional) {
        for (let key in paras.additional) {
            dataStr += '&' + key + '=' + paras.additional[key];
        }
    }
    const origin = getQueryString('origin')
    if(origin)dataStr+='&ro='+origin
    /* 新埋点请求 */
    setNewPv(dataStr)
    /* 新埋点请求 */
}
const newPvTransferTools = (oldKey = '')=> {
    let keysArr = [//新老键名对比
        { old: 'page_id', new: 'pid' },
        { old: 'referer', new: 'r' },
        { old: 'origin', new: 'ro' },
        { old: 'keyword', new: 'kw' },
        { old: 'abType', new: 'ab' },
        { old: 'templ_id', new: 'ti' },
        { old: 'user_templ_id', new: 'ut' },
        { old: 'load_time', new: 'i0' },
        { old: 'class_id', new: 'ki' },
        { old: 'route_id', new: 'ri' },
        { old: 'route', new: 'rb' },
        { old: 'after_route', new: 'ra' },
        { old: 'dom_load_time', new: 'dom_load_time' },
        { old: 'img_load_time', new: 'img_load_time' },
    ],
        resKey = oldKey;

    for (let i = 0, len = keysArr.length; i < len; ++i) {
        let item = keysArr[i]
        if (oldKey == item.old) {
            resKey = item.new
            break;
        }
    }
    return resKey
}
const setNewPv = (dataStr = '', options = {})=> {
    let paramsArr = dataStr.split('&'),
        newParams = [], newParamsStr = '', deleteParams = ['pram', 'option', 'type'] /* 需要删除的属性*/;
    paramsArr.map(v => {
        let itemArr = v.split('='),
            newKey = newPvTransferTools(itemArr[0]);
        /*过滤控制 和值等于 undefined的  */
        if (itemArr[1] && itemArr[1] != 'undefined' && itemArr[1] != 'NaN' && deleteParams.indexOf(newKey) < 0) {
            newParams.push(`${newKey}=${itemArr[1]}`)
        }
    })
    /* 获取cookie */
    let userInfoCookie = '';
    userInfoCookie = getCookie('ui_818ps');
    userInfoCookie ? userInfoCookie = encodeURIComponent(userInfoCookie) : '';
    /* 获取cookie */
    userInfoCookie && newParams.push(`ui=${userInfoCookie}`)//用户信息
    newParams.push(`pt=web`)//站点信息
    newParams.push(`u=${encodeURIComponent('' + location.href)}`)//用户地址信息
    newParams.push(`v=${new Date().getTime()}`)//添加时间戳
    newParamsStr = newParams.join('&')
    return fetch('//p.818ps.com/p.gif?' + newParamsStr, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        mode: "no-cors",//后台做过配置 设置为cors会报错
        ...options
    }).catch(error => {
        // 捕获错误，防止影响其他功能
    });
}

export default () => { }